import { Table } from 'antd';
import type { TableColumnsType } from 'antd';
import type React from 'react';
import { useEffect, useState } from 'react';

interface TradeDataType {
  key: React.Key;
  tradeDate: string;
  tradeType: 'Deposit' | 'Withdrawal' | 'Transfer';
  amount: number;
  balance: number;
  remark?: string;
}

interface CardTradeTableProps {
  cardID: string;
  refreshTrigger?: number;
}

const columns: TableColumnsType<TradeDataType> = [
  {
    title: '交易日期',
    dataIndex: 'tradeDate',
  },
  {
    title: '交易类型',
    dataIndex: 'tradeType',
    render: (type: string) => {
      if (type === 'Deposit') return '存款';
      if (type === 'Withdrawal') return '取款';
      return '转账';
    },
  },
  {
    title: '交易金额',
    dataIndex: 'amount',
  },
  {
    title: '余额',
    dataIndex: 'balance',
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
];

function CardTradeTable({ cardID, refreshTrigger }: CardTradeTableProps) {
  const [trades, setTrades] = useState<TradeDataType[]>([]);

  useEffect(() => {
    if (cardID) {
      fetch(`http://localhost:8000/trades/by-card/${cardID}`)
        .then((response) => response.json())
        .then((data) => {
          const formattedData = data.map((trade: any) => {
            let tradeType: 'Deposit' | 'Withdrawal' | 'Transfer';
            if (trade.tradeType === '存入') {
              tradeType = 'Deposit';
            } else if (trade.tradeType === '支取') {
              tradeType = 'Withdrawal';
            } else {
              tradeType = 'Transfer';
            }
            return {
              key: trade.tradeID,
              tradeDate: new Date(trade.tradeDate).toLocaleString(),
              tradeType: tradeType,
              amount: trade.tradeMoney,
              balance: trade.current_balance,
              remark: trade.remark,
            };
          });
          setTrades(formattedData);
        })
        .catch((error) => console.error('Error fetching trade data:', error));
    }
  }, [cardID, refreshTrigger]);

  return <Table columns={columns} dataSource={trades} />;
}

export default CardTradeTable;
